# encoding=utf-8
import os
import logging
from logging.handlers import TimedRotatingFileHandler
import yaml


class AppConfig:
    # 常规配置
    PROJECT_PATH = os.path.join(os.path.dirname(__file__))
    RESOURCES_PATH = os.path.join(PROJECT_PATH, "AppConfig.yaml")
    CACHE_PATH = os.path.join(PROJECT_PATH, "runtime-cache")
    LOGGER_PATH = os.path.join(PROJECT_PATH, "runtime-log")

    SQL_TABLE_NAME = "convert"
    PID_FILE = "interval-pid.pid"


os.makedirs(AppConfig.CACHE_PATH, exist_ok=True)
os.makedirs(AppConfig.LOGGER_PATH, exist_ok=True)

with open(AppConfig.RESOURCES_PATH, "r", encoding='utf-8') as f:
    _y = yaml.safe_load(f)
    SQL_NAME = _y["SQL_NAME"]
    FROM_PATH = _y["FROM_PATH"]
    TO_PATH = _y["TO_PATH"]
    DST_NAME_TEMPLATE = _y["DST_NAME_TEMPLATE"]
    DST_NAME_S_TEMPLATE = _y["DST_NAME_S_TEMPLATE"]
    LOOP_INTERVAL = _y["LOOP_INTERVAL"]
    LEFT_IDENTY = _y["LEFT_IDENTY"]
    RIGHT_IDENTY = _y["RIGHT_IDENTY"]
    SLEEP_TIME = _y["SLEEP_TIME"]
    NEED_ORI = int(_y["NEED_ORI"])

    assert DST_NAME_S_TEMPLATE != ""
    assert SQL_NAME != ""
    assert FROM_PATH != ""
    assert TO_PATH != ""
    assert DST_NAME_TEMPLATE != ""
    assert LOOP_INTERVAL != ""
    assert LEFT_IDENTY != ""
    assert RIGHT_IDENTY != ""
    assert SLEEP_TIME != ""


# 日志配置
def set_logger():
    logger = logging.getLogger()  # root
    logger.setLevel(logging.INFO)

    file_handler = TimedRotatingFileHandler(
        filename=os.path.join(AppConfig.LOGGER_PATH, "app-log"),
        when='D', interval=1
    )
    file_handler.suffix = "%Y-%m-%d.log"

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)

    logging_format = logging.Formatter(
        "%(asctime)s - %(filename)s - %(funcName)s - %(lineno)d - %(levelname)s - %(message)s")

    file_handler.setFormatter(logging_format)
    console_handler.setFormatter(logging_format)

    logger.addHandler(file_handler)
    logger.addHandler(console_handler)


set_logger()
